package com.dk.service.impl;

import com.dk.mapper.RoleUserMapper;
import com.dk.mapper.UserMapper;
import com.dk.pojo.RoleUserExample;
import com.dk.pojo.User;
import com.dk.service.UserService;
import com.dk.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    RoleUserMapper roleUserMapper;


    @Override
    public List<User> getInfo() {
        return userMapper.selectByExample(null);
    }

    @Override
    public int insertInfo(Integer[] rid, User user) {
        try {
            String encryptedPwd = MD5Utils.getEncryptedPwd("123");
            user.setPassword(encryptedPwd);
            int i = userMapper.insertUserReturnPrimaryKey(user);
            Integer uid = user.getUid();
            int uidAndRid = roleUserMapper.insertUidAndRid(rid,uid);
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            try {
                throw e;
            } catch (Exception noSuchAlgorithmException) {
                noSuchAlgorithmException.printStackTrace();

            }
        }
        return 0;
    }

    @Override
    public User getInfoByUid(Integer uid) {

        return userMapper.selectByPrimaryKey(uid);
    }

    @Override
    public int updateUserInfo(User user, Integer[] rid) {
        try {
            userMapper.updateByPrimaryKeySelective(user);
            //根据uid删除对应用户角色中间表的rid
            RoleUserExample example = new RoleUserExample();
            RoleUserExample.Criteria criteria = example.createCriteria();
            criteria.andUidEqualTo(user.getUid());
            roleUserMapper.deleteByExample(example);
            //重新插入新的rid
            roleUserMapper.insertUidAndRid(rid,user.getUid());
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }

    }

    @Override
    public int deleteInfoByUid(Integer uid) {
        return userMapper.deleteByPrimaryKey(uid);
    }

    @Override
    public void updateFlag(User user) {
        userMapper.updateByPrimaryKeySelective(user);
    }
}
